package fun.zhufn.oldcomm;

import fun.zhufn.oldcomm.model.bo.User;
import fun.zhufn.oldcomm.model.bo.customlist.UserList;
import fun.zhufn.oldcomm.model.service.UserManagerService;
import fun.zhufn.oldcomm.view.RootDesk;

import javax.swing.*;
import java.util.logging.Logger;

public class UserManagerController {
    private static final UserManagerController INSTANCE = new UserManagerController();
    private static final Logger log = Logger.getLogger(UserManagerController.class.toString());


    /**
     * 退出
     */
    public void logOut() {
        UserManagerService.getInstance().setUser(null);
    }

    /**
     * @return 登录用户
     */
    public User getUser() {
        return UserManagerService.getInstance().getUser();
    }

    /**
     * @return 用户列表
     */
    public UserList getSavedUserListOrDefault() {
        UserList users_l = UserManagerService.getInstance().getUserList();
        if (users_l.getData().isEmpty()) {
            log.info("无用户，生成默认管理员用户root密码123");
            JOptionPane.showMessageDialog(null, "无用户，生成默认管理员用户root密码123");
            addUser(new User(
                    "root", "123", "root", "00000000", "00000000000", true, 3
            ));
            users_l = UserManagerService.getInstance().getUserList();
        }
        return users_l;
    }

    /**
     * @param father 父JFrame
     * @param username 用户名
     * @param pwd 密码
     */
    public void doLogin(JFrame father, String username, String pwd) {
        String res = UserManagerService.getInstance().doLogin(username, pwd);
        if (res.equals("OK")) {
            JOptionPane.showMessageDialog(null, "登录成功！");
            User v = getUser();
            father.dispose();
            new RootDesk().start();
        } else {
            log.info(res);
            JOptionPane.showMessageDialog(null, res);
        }
    }

    /**
     * @param u 用户
     * @return 是否成功
     */
    public boolean addUser(User u){
        return UserManagerService.getInstance().addUser(u);
    }

    /**
     * @param acc 用户
     * @return 是否成功
     */
    public boolean removeUser(String acc) {
        return UserManagerService.getInstance().removeUser(acc);
    }

    private UserManagerController() {}

    public static UserManagerController getInstance() {
        return INSTANCE;
    }

    /**
     * @param acc 用户账号
     * @return 用户
     */
    public User getUserByAccount(String acc) {
        var ul = UserManagerService.getInstance().getUserList().getData();
        for (var u: ul){
            if (u.getAccount().equals(acc)) {
                return u;
            }
        }
        return null;
    }

    /**
     * @param u 用户
     * @return 是否成功
     */
    public boolean editUser(User u) {
        if (removeUser(u.getAccount()))
            return addUser(u);
        else return false;
    }
}
